import 'package:eh_mobile/global.dart';
import 'package:eh_mobile/pages/main/homepage/model/home_device_model.dart';
import 'package:eh_mobile/pages/main/smart_home_info/state.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/store/user_store.dart';
import '../../../common/utils/enums.dart';
import '../../../common/utils/web_rtc_channel_common.dart';
import '../../control/light_control/index.dart';
import '../../control/temp_control/temp_control_view.dart';

class SmartHomeInfoController extends GetxController {
  //导航
  String smartHomeInfoId = 'smart_home_info';

  // 页面状态
  final SmartHomeInfoState state = SmartHomeInfoState();

  // 是否是点击上方tab
  var isTabClicked = false;

  final roomList = [];

  final scrollController = ScrollController();

  final editOpen = false.obs;

  //标题栏
  final subTitle = ''.obs;

  final subTitleHidden = true.obs;

  late List<List<HomeDeviceModelDevices>> lightList = [];

  /// 房间标题GlobalKey，用于锚点
  final List<GlobalKey<State<StatefulWidget>>> roomTitleGlobalKeys =
      <GlobalKey>[];

  // 设备列表类型
  late DeviceLListType deviceLListType = Get.arguments;

  // 灯光卡片被点击
  void lightCardItemAction(int index, String name) {
    if (deviceLListType == DeviceLListType.light) {
      Get.to(const LightControlPage(), arguments: name);
    } else {
      Get.to(const TempControlPage(), arguments: name);
    }
  }

  @override
  void onInit() {
    super.onInit();
  }

  void handleDataFromSection(List<HomeDeviceModelDevices>? devices) {
    List temps = ['1F客厅空调', '2F客厅空调', '1F主卧地暖', '2F次卧空调', '2F次卧地暖'];
    //把数据进行分区
    for (String region in roomList) {
      List<HomeDeviceModelDevices> sectionList = [];
      devices?.forEach((HomeDeviceModelDevices allDevice) {
        sectionList.addIf(allDevice.region_name == region, allDevice);
      });
      lightList.add(sectionList);
    }

    //给数据加标识
    for (var i = 0; i < roomList.length; i++) {
      var list = lightList[i];
      for (var j = 0; j < list.length; j++) {
        var model = list[j];
        // if (model.all_config != null &&
        //     model.all_config?.writeProperties != null) {
        //   model.cardOpen =
        //       model.all_config?.writeProperties?.contains('light_bright');
        // } else {
        // model.cardOpen = false;
        //  }
        model.colorTemp = 800;
        model.hasEvent = model.last?.power == 'on';
        double brightness = model.last?.light_bright?.toDouble() ?? 0;
        model.brightness = brightness / 100;
        model.tempValue = 25.5;
        model.currentTempValue = 29.5;
      }
    }

    for (var i = 0; i < roomList.length; i++) {
      roomTitleGlobalKeys.add(GlobalKey(debugLabel: 'title$i'));
    }
    scrollController.addListener(scrollViewDidScroll);
  }

  void scrollViewDidScroll() {
    if (scrollController.offset > 0 && !state.scrollViewDidScroll) {
      state.scrollViewDidScroll = true;
    } else if (scrollController.offset <= 0 && state.scrollViewDidScroll) {
      state.scrollViewDidScroll = false;
    }
  }

  // 顶部房间item点击事件
  void onTabChange(index) {
    RenderObject? keyRenderObject = roomTitleGlobalKeys[index]
        .currentContext
        ?.findAncestorRenderObjectOfType();
    if (keyRenderObject != null) {
      isTabClicked = true;
      Scrollable.ensureVisible(roomTitleGlobalKeys[index].currentContext!,
              duration: const Duration(milliseconds: 300), curve: Curves.easeIn)
          .then((value) {
        isTabClicked = false;
      });
    }
  }

  // 全部开启关闭点击
  void allControlDeviceClick(bool lightOpen) {
    String isOn = lightOpen ? 'on' : 'off';
    for (var element in lightList) {
      for (var cardModel in element) {
        if (cardModel.online!) {
          WebRtcChannelCommon.sendChannelDeviceWrite(
              Global.webRtcChannel.sendChannel,
              item: cardModel,
              dataMap: {'power': isOn});
          cardModel.last?.power = isOn;
          cardModel.hasEvent = lightOpen;
        }
      }
    }
    update([smartHomeInfoId]);
  }

  // 关闭某一组区域灯光
  void sectionControlDeviceClick(int index, bool lightOpen) {
    String isOn = lightOpen ? 'on' : 'off';
    for (var cardModel in lightList[index]) {
      if (cardModel.online!) {
        WebRtcChannelCommon.sendChannelDeviceWrite(
            Global.webRtcChannel.sendChannel,
            item: cardModel,
            dataMap: {'power': isOn});
        cardModel.last?.power = isOn;
        cardModel.hasEvent = lightOpen;
      }
    }
    update([roomList[index]]);
  }

  // 判断某一组灯光是否全部关闭
  bool judgeSectionAllDeviceIsClose(int index) {
    for (var cardModel in lightList[index]) {
      //判断在线且有灯是开启状态
      if (cardModel.online! && cardModel.hasEvent!) {
        return true;
      }
    }
    return false;
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    scrollController.removeListener(scrollViewDidScroll);
    scrollController.dispose();
    super.onClose();
  }

  void saveDataToLocal() {
    List list = [];
    for (int i = 0; i < roomList.length; i++) {
      List sectionList = lightList[i];
      for (int j = 0; j < sectionList.length; j++) {
        HomeDeviceModelDevices allModel = sectionList[j];
        list.add(allModel);
      }
    }
    UserStore().userStoreCache.write('light', list);
  }
}
